/**
 * 缓存
 */
import { defineStore } from 'pinia';
import router from '@/router';

// 根据数组的下标，删除该下标的元素
const remove = (list, val) => {
  const index = list.indexOf(val);
  if (index > -1) {
    list.splice(index, 1);
  }
  return list;
};

export const XmRouter = defineStore('XmRouter', {
  state: () => ({
    keepAlive: []
  }),
  actions: {
    push(name) {
      if (name && this.keepAlive.indexOf(name) < 0) this.keepAlive.push(name);
    },
    remove(name) {
      if (name) remove(this.keepAlive, name);
    },
    clear() {
      this.keepAlive = [];
    },
    back() {
      const route = router.currentRoute;
      const name = route.value.name;
      if (name) this.remove(name);
      router.back();
    }
  }
});

export const useXmRouter = () => {
  return XmRouter();
};
